package cn.com.surker.system.service.impl;

import cn.com.surker.base.BaseEntity;
import cn.com.surker.base.system.dao.*;
import cn.com.surker.base.system.entity.*;
import cn.com.surker.common.MessageCenterException;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.dto.system.SysStorageMatchDTO;
import cn.com.surker.enums.base.StorageEnjoyTypeEnum;
import cn.com.surker.enums.control.ControlFlagEnum;
import cn.com.surker.enums.material.MaterialInventoryEnum;
import cn.com.surker.enums.material.SysMaterialTypeEnum;
import cn.com.surker.enums.oa.CarTypeEnum;
import cn.com.surker.enums.weight.OrderWeightTypeEnum;
import cn.com.surker.enums.weight.WeightCarTypeEnum;
import cn.com.surker.enums.weight.WeightTypeEnum;
import cn.com.surker.lab.dao.LabExpendDao;
import cn.com.surker.lab.dao.LabExpendOtherDao;
import cn.com.surker.material.dao.MainMaterialDao;
import cn.com.surker.material.dao.MainMaterialHistoryInventoryDao;
import cn.com.surker.material.dao.MainMaterialWeightDao;
import cn.com.surker.material.entity.MainMaterial;
import cn.com.surker.material.entity.MainMaterialHistoryInventory;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.system.model.CacheUser;
import cn.com.surker.system.service.SysStorageMatchService;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import cn.com.surker.vo.system.SysStorageMatchVO;
import cn.com.surker.workcon.service.StorERPMaterService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.snaker.engine.SnakerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SysStorageMatchServiceImpl implements SysStorageMatchService {

    @Resource
    private SysStorageMatchDao mapper;
    @Resource
    private SysStorageDao sysStorageDao;
    @Resource
    private MainMaterialDao mainMaterialDao;
    @Resource
    private SysControlStorageDao sysControlStorageDao;
    @Resource
    private SysLineDao sysLineDao;
    @Resource
    private SysStorageLogDao storageLogDao;
    @Resource
    private MainMaterialHistoryInventoryDao historyInventoryDao;
    @Resource
    private MainMaterialWeightDao materialWeightDao;
    @Resource
    private LabExpendOtherDao expendOtherDao;
    @Resource
    private LabExpendDao expendDao;
	@Autowired
	private StorERPMaterService storERPMaterService;


    @Override
    public IPage<SysStorageMatchVO> page(SysStorageMatchDTO dto) {
        PageHelper.offsetPage(dto.getOffsetSize(), dto.getLimit());
        Page<SysStorageMatchVO> page = new Page<>(dto.getCurrSize(), dto.getLimit());
        IPage<SysStorageMatchVO> iPage = mapper.page(page, dto);
        /**分页插件**/
        if (ObjectUtil.isNotEmpty(iPage)) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal())) iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }

    @Override
    public RestResultDto add(SysStorageMatchDTO dto, CacheUser user) {
        if (dto == null)
            throw new MessageCenterException("参数错误");
        if (StringUtils.isNull(dto.getStorageId()))
            throw new MessageCenterException("ERP仓位为空");
        if (StringUtils.isNull(dto.getLineId()))
            throw new MessageCenterException("生产线ID为空");
        if (StringUtils.isNull(dto.getMaterialId()))
            throw new MessageCenterException("材料ID为空");
        if (StringUtils.isAllParamNull(dto.getControlId(), dto.getControlStorage()))
            throw new MessageCenterException("工控仓位信息为空");
        MainMaterial material = mainMaterialDao.findByMaterialId(dto.getMaterialId());
        if (material == null || material.getStatus().intValue() == 1)
            throw new MessageCenterException("材料信息不存在或已被禁用");
        Date nowDate = new Date();
        String takeTime = dto.getTakeTime();
        if (StringUtils.isNull(takeTime))
            takeTime = DateUtil.convertString(nowDate);
        SysStorageMatch sysStorageMatch = BeanUtil.copyProperties(dto, SysStorageMatch.class);
        Integer total = mapper.findExistMatch(sysStorageMatch.getOrgId(), sysStorageMatch.getLineId(),
                sysStorageMatch.getStorageId(), sysStorageMatch.getControlId());
        if (total > 0)
            throw new MessageCenterException("同一生产线、同一仓位、同一工控仓位已有关联信息,可设置修改信息");
        SysStorage sysStorage = sysStorageDao.selectById(sysStorageMatch.getStorageId());//查询ERP仓位
        if (sysStorage == null || sysStorage.getStatus() == 1)
            throw new MessageCenterException("ERP仓位不存在或已被禁用");
        if (material.getStoreType().intValue() != sysStorage.getType())
            throw new MessageCenterException("ERP仓位类型与材料材料仓位类型不匹配");
        if (StringUtils.isNull(sysStorage.getMaterialId()))
            throw new MessageCenterException("ERP仓位未设置材料信息");
        if (!StringUtils.isNull(sysStorage.getMaterialId()) && dto.getMaterialId().longValue() != sysStorage.getMaterialId().longValue())
            throw new MessageCenterException("ERP仓位材料信息与关联材料信息不匹配");
        SysControlStorage controlStorage = sysControlStorageDao.selectById(sysStorageMatch.getControlId());//查询工控仓位
        if (controlStorage == null || controlStorage.getStatus() == 1)
            throw new MessageCenterException("工控仓位不存在或已被禁用");

        if (material.getType().intValue() == SysMaterialTypeEnum.SN.getCode().intValue()) {//如果是参合料、水泥
//        if (material.getType().intValue() == SysMaterialTypeEnum.SN.getCode().intValue()
//                || material.getType().intValue() == SysMaterialTypeEnum.CHL.getCode().intValue()) {//如果是参合料、水泥
            SysStorageMatchDTO matchDTO = new SysStorageMatchDTO();
            matchDTO.setControlId(sysStorageMatch.getControlId());
            matchDTO.setStatus(0);
            List<SysStorageMatchVO> matchVOList = mapper.page(matchDTO);
            if (matchVOList != null && matchVOList.size() > 0)
                throw new MessageCenterException("水泥、参合料工控仓位只能关联一次,请查找到原有仓位修改");
            matchDTO = new SysStorageMatchDTO();
            matchDTO.setStorageId(sysStorageMatch.getStorageId());
            matchDTO.setStatus(0);
            matchVOList = mapper.page(matchDTO);
            if (matchVOList != null && matchVOList.size() > 0)
                throw new MessageCenterException("水泥、参合料ERP仓位只能关联一次,请查找到原有仓位修改");
        }

        SysLine line = sysLineDao.selectById(sysStorageMatch.getLineId());
        if (line == null || line.getStatus() == 1)
            throw new MessageCenterException("生产线不存在或已被删除");
        sysStorageMatch.setStatus(0);
        sysStorageMatch.setCreator(user.getName());
        sysStorageMatch.setCreateTime(nowDate);
        Integer code = mapper.insert(sysStorageMatch);
        if (code > 0) {
            Integer storageCode = saveStorageLog(sysStorageMatch.getOrgId(), sysStorage.getId(), sysStorage.getName(),
                    sysStorage.getName(), material.getMaterialId(), material.getNameNorms(),
                    line.getId(), 0, nowDate, user.getName(), nowDate);
            if (storageCode != 0)
                throw new MessageCenterException("更新ERP仓位变更记录错误");
            storageCode = saveStorageLog(sysStorageMatch.getOrgId(), controlStorage.getId(), controlStorage.getName(),
                    controlStorage.getName(), material.getMaterialId(), material.getNameNorms(),
                    line.getId(), 1, nowDate, user.getName(), nowDate);
            if (storageCode != 0)
                throw new MessageCenterException("更新ERP仓位变更记录错误");

            MainMaterialHistoryInventory  historyInventory = historyInventoryDao.findByStoreId(sysStorageMatch.getStorageId());
            String saveTip = "";
            if (historyInventory == null) {
                saveTip = "仓位:" + sysStorage.getName() + "\n材料:" + material.getNameNorms() + "\n期初值:0吨,购进值:0吨,消耗值:0吨,目前库存:0吨\n生效时间:" + takeTime;
                historyInventory = new MainMaterialHistoryInventory(sysStorageMatch.getOrgId(), sysStorageMatch.getMaterialId(),
                        sysStorageMatch.getStorageId(), DateUtil.convertDate(takeTime), nowDate, 0.0, 0.0, 0.0,
                        0.0, MaterialInventoryEnum.CWHL.getCode(), sysStorageMatch.getControlId());
            } else {
                String startTime = DateUtil.convertString(historyInventory.getStartDate());
                String endTime = DateUtil.convertString(nowDate);
                //自动消耗
                Double autoDosage = expendDao.findSumDosage(sysStorageMatch.getStorageId(), sysStorageMatch.getMaterialId(), startTime, endTime);
                //手动消耗
                Double handDosage = expendOtherDao.findSumOtherDosage(sysStorageMatch.getStorageId(), sysStorageMatch.getMaterialId(), startTime, endTime);
                //购进总数
                Double netWeight = materialWeightDao.findSumNetWeight(sysStorageMatch.getStorageId(), sysStorageMatch.getMaterialId(),
                        WeightCarTypeEnum.MATERIAL.getCode(), OrderWeightTypeEnum.YC.getCode(), startTime, endTime);
                Double initial = historyInventory.getInitial() + historyInventory.getAdjustment() + netWeight - autoDosage - handDosage;
                historyInventory.setCrease(netWeight);
                historyInventory.setReduse(autoDosage + handDosage);
                historyInventory.setCheckDate(DateUtil.convertDate(takeTime));
                historyInventory.setUpdateTime(nowDate);
                historyInventory.setUpdator(user.getName());
                historyInventoryDao.updateById(historyInventory);//保存原有盘存数据
                saveTip = "仓位:" + sysStorage.getName() + "\n材料:" + material.getNameNorms() + "\n期初值:" + StringUtils.formatDouble(historyInventory.getInitial() / 1000, 2)
                        + "吨,调整值:" + StringUtils.formatDouble(historyInventory.getAdjustment() / 1000, 2)
                        + "吨,购进值:" + StringUtils.formatDouble(netWeight / 1000, 2)
                        + "吨,消耗值:" + StringUtils.formatDouble((autoDosage + handDosage) / 1000, 2)
                        + "吨,目前库存:" + StringUtils.formatDouble(initial / 1000, 2) + "吨\n生效时间:" + takeTime;

                historyInventory.setId(null);
                historyInventory.setMaterialId(sysStorageMatch.getMaterialId());
                historyInventory.setCreator(user.getName());
                historyInventory.setInitial(initial);
                historyInventory.setAdjustment(0.0);
                historyInventory.setCrease(0.0);
                historyInventory.setReduse(0.0);
                historyInventory.setStartDate(DateUtil.convertDate(takeTime));
                historyInventory.setCheckDate(nowDate);
                historyInventory.setStoreId(sysStorageMatch.getStorageId());
                historyInventory.setControlStoreId(sysStorageMatch.getControlId());
            }
            historyInventory.setCreateTime(nowDate);
            historyInventory.setRemark(material.getNameNorms() + "仓位换料盘点记录");
            if (!StringUtils.isNull(historyInventory.getId()) && sysStorage.getIsEnjoy().intValue() == 1) {//如果不是共享仓
                historyInventory.setId(null);
                code = historyInventoryDao.insert(historyInventory);
                if (code < 1)
                    throw new MessageCenterException("保存换料盘点记录错误");
            } else {
                code = historyInventoryDao.insert(historyInventory);
                if (code < 1)
                    throw new MessageCenterException("保存换料盘点记录错误");
            }
            controlStorage.setMaxCapacity(sysStorage.getMaxCapacity());
            controlStorage.setFlag(ControlFlagEnum.ZC.getCode() + "");
            controlStorage.setControlCreateTime(DateUtil.convertString(nowDate));
			Long controlId = storERPMaterService.insertErpStore(line, controlStorage);
            if (controlId > 0) {
                if (!StringUtils.isNull(takeTime)) {
                    sysStorage.setInventoryTime(DateUtil.convertDate(takeTime));
                    sysStorage.setUpdateTime(nowDate);
                    sysStorage.setUpdator(user.getName());
                    sysStorageDao.updateById(sysStorage);
                }

                sysStorageMatch.setRelatedId(controlId);
                code = mapper.updateById(sysStorageMatch);
                if (code > 0)
                    return RestResultDto.success(saveTip);
                throw new MessageCenterException("保存工控系统仓位关联信息异常");
            }
            //同步写入工控仓位信息代码
//            StorERPMater stor = new StorERPMater(line.getControlLineId().intValue(), controlStorage.getName(),
//                    controlStorage.getMaterialName(), sysStorage.getMaxCapacity(), nowDate, ControlFlagEnum.ZC.getCode());
//            code = storERPMaterDao.insert(stor);
//            if (code > 0) {
//                sysStorageMatch.setRelatedId(stor.getId());
//                code = mapper.updateById(sysStorageMatch);
//                if (code > 0)
//                    return RestResultDto.success("保存成功");
//                throw new MessageCenterException("保存工控系统仓位关联信息异常");
//            }
        }
        throw new MessageCenterException("保存ERP仓位与工控仓位关联信息异常");
    }

    @Override
    public RestResultDto edit(SysStorageMatchDTO dto, CacheUser user) {
        if (ObjectUtil.isEmpty(dto.getId())) {
            throw new MessageCenterException("标识不存在，请检查数据！");
        }
        if (StringUtils.isNull(dto.getMaterialId()))
            throw new MessageCenterException("更新材料为空");
        SysStorageMatch sysStorageMatch = mapper.selectById(dto.getId());
        if (ObjectUtil.isEmpty(sysStorageMatch)) {
            throw new MessageCenterException("当前工控仓位数据不存在，请重新处理！");
        }
        Long oldMaterialId = sysStorageMatch.getMaterialId();
        Long oldStorageId = sysStorageMatch.getStorageId();
        Long oldControlId = sysStorageMatch.getControlId();
        String takeTime = dto.getTakeTime();
        Date nowDate = new Date();
        if (StringUtils.isNull(takeTime))
            takeTime = DateUtil.convertString(nowDate);
        if (StringUtils.isNull(sysStorageMatch.getRelatedId()) || sysStorageMatch.getRelatedId() < 1)
            throw new SnakerException("工控系统仓位关联数据不存在，请重新处理！");
//        if (sysStorageMatch.getMaterialId().intValue() == dto.getMaterialId().intValue())
//            throw new MessageCenterException("原数据材料与更新材料没有变化");
        if (StringUtils.isAllParamNull(dto.getControlId(), dto.getControlStorage()))
            throw new MessageCenterException("工控仓位信息为空");
        MainMaterial material = mainMaterialDao.findByMaterialId(dto.getMaterialId());
        if (material == null || material.getStatus().intValue() == 1)
            throw new MessageCenterException("材料信息不存在或已被禁用");
        SysControlStorage controlStorage = sysControlStorageDao.selectById(dto.getControlId());
        if (controlStorage == null || controlStorage.getStatus() == 1)
            throw new MessageCenterException("工控仓位信息不存在或已被禁用");
        SysLine line = sysLineDao.selectById(sysStorageMatch.getLineId());
        if (line == null || line.getStatus() == 1)
            throw new MessageCenterException("生产线不存在或已被删除");
        if (material.getType().intValue() == SysMaterialTypeEnum.SN.getCode().intValue()) {//如果是参合料、水泥
//        if (material.getType().intValue() == SysMaterialTypeEnum.SN.getCode().intValue()
//                || material.getType().intValue() == SysMaterialTypeEnum.CHL.getCode().intValue()) {//如果是参合料、水泥
            if (!StringUtils.isNull(dto.getControlId()) && dto.getControlId().longValue() != oldControlId.longValue()) {
                SysStorageMatchDTO matchDTO = new SysStorageMatchDTO();
                matchDTO.setControlId(sysStorageMatch.getControlId());
                matchDTO.setStatus(0);
                List<SysStorageMatchVO> matchVOList = mapper.page(matchDTO);
                if (matchVOList != null && matchVOList.size() > 0)
                    throw new MessageCenterException("水泥、参合料工控仓位只能关联一次,请查找到原有仓位修改");
            }
            if (!StringUtils.isNull(dto.getStorageId()) && dto.getStorageId().longValue() != oldStorageId.longValue()) {
                SysStorageMatchDTO matchDTO = new SysStorageMatchDTO();
                matchDTO.setStorageId(sysStorageMatch.getStorageId());
                matchDTO.setStatus(0);
                List<SysStorageMatchVO> matchVOList = mapper.page(matchDTO);
                if (matchVOList != null && matchVOList.size() > 0)
                    throw new MessageCenterException("水泥、参合料ERP仓位只能关联一次,请查找到原有仓位修改");
            }
        }

//        BeanUtil.copyProperties(dto, sysStorageMatch);
        Long newMaterialId = dto.getMaterialId();
        Long newStorageId = dto.getStorageId();
        Long newControlStorageId = dto.getControlId();
        sysStorageMatch.setMaterialId(dto.getMaterialId());
        sysStorageMatch.setStorageId(dto.getStorageId());
        sysStorageMatch.setControlId(dto.getControlId());
        sysStorageMatch.setControlStorage(dto.getControlStorage());
        sysStorageMatch.setUpdateTime(nowDate);
        sysStorageMatch.setUpdator(user.getName());
        Integer code = mapper.updateById(sysStorageMatch);
        if (code > 0) {
            SysStorage sysStorage = sysStorageDao.selectById(sysStorageMatch.getStorageId());//查询ERP仓位
            if (sysStorage == null || sysStorage.getStatus() == 1)
                throw new MessageCenterException("ERP仓位不存在或已被禁用");
            if (StringUtils.isNull(sysStorage.getMaterialId()))
                throw new MessageCenterException("ERP仓位未设置材料信息");
            if (material.getStoreType().intValue() != sysStorage.getType())
                throw new MessageCenterException("ERP仓位类型与材料材料仓位类型不匹配");
            if (!StringUtils.isNull(sysStorage.getMaterialId()) && dto.getMaterialId().longValue() != sysStorage.getMaterialId().longValue())
                throw new MessageCenterException("ERP仓位材料信息与关联材料信息不匹配");
            if (sysStorage.getId().longValue() != oldStorageId.longValue()
                    || material.getMaterialId().longValue() != oldMaterialId.longValue()) {
                Integer storageCode = saveStorageLog(sysStorageMatch.getOrgId(), sysStorage.getId(), sysStorage.getName(),
                        sysStorage.getName(), material.getMaterialId(), material.getNameNorms(),
                        line.getId(), 0, DateUtil.convertDate(takeTime), user.getName(), nowDate);
                if (storageCode != 0)
                    throw new MessageCenterException("更新ERP仓位变更记录错误");
            }
            if (sysStorage.getId().longValue() != oldControlId.longValue()
                    || material.getMaterialId().longValue() != oldMaterialId.longValue()) {
                Integer storageCode = saveStorageLog(sysStorageMatch.getOrgId(), controlStorage.getId(), controlStorage.getName(),
                        controlStorage.getName(), material.getMaterialId(), material.getNameNorms(),
                        line.getId(), 1, DateUtil.convertDate(takeTime), user.getName(), nowDate);
                if (storageCode != 0)
                    throw new MessageCenterException("更新ERP仓位变更记录错误");
            }

            MainMaterialHistoryInventory  historyInventory = historyInventoryDao.findByStoreId(sysStorageMatch.getStorageId());
            String remark = material.getNameNorms() + "仓位换料盘点记录";
            String saveTip = "";
            if (historyInventory == null) {
                saveTip = "仓位:" + sysStorage.getName() + "\n材料:" + material.getNameNorms() + "\n期初值:0吨,购进值:0吨,消耗值:0吨,目前库存:0吨\n生效时间:" + takeTime;
                historyInventory = new MainMaterialHistoryInventory(sysStorageMatch.getOrgId(), dto.getMaterialId(),
                        sysStorageMatch.getStorageId(), DateUtil.convertDate(takeTime), nowDate, 0.0, 0.0, 0.0,
                        0.0, MaterialInventoryEnum.CWHL.getCode(), sysStorageMatch.getControlId());
            } else {
                if (newMaterialId == historyInventory.getMaterialId()
                        && newStorageId == historyInventory.getStoreId()
                        && newControlStorageId == historyInventory.getControlStoreId())
                    throw new MessageCenterException("ERP仓位、工控仓位、材料未发生变化");
                historyInventory.setId(null);
                if (newMaterialId != historyInventory.getMaterialId())
                    remark += historyInventory.getMaterialId() + "-->" + newMaterialId + "\t";
                if (newStorageId != historyInventory.getStoreId())
                    remark += historyInventory.getControlStoreId() + "-->" + newStorageId + "\t";
                if (newControlStorageId != historyInventory.getControlStoreId())
                    remark += historyInventory.getControlStoreId() + "-->" + newControlStorageId + "\t";
                String startTime = DateUtil.convertString(historyInventory.getStartDate());
                String endTime = DateUtil.convertString(nowDate);
                //自动消耗
                Double autoDosage = expendDao.findSumDosage(newStorageId, newMaterialId, startTime, endTime);
                //手动消耗
                Double handDosage = expendOtherDao.findSumOtherDosage(newStorageId, newMaterialId, startTime, endTime);
                //购进总数
                Double netWeight = materialWeightDao.findSumNetWeight(newStorageId, newMaterialId,
                        WeightCarTypeEnum.MATERIAL.getCode(), OrderWeightTypeEnum.YC.getCode(), startTime, endTime);
                Double initial = historyInventory.getInitial() + historyInventory.getAdjustment() + netWeight - autoDosage - handDosage;
                historyInventory.setCrease(netWeight);
                historyInventory.setReduse(autoDosage + handDosage);
                historyInventory.setCheckDate(DateUtil.convertDate(takeTime));//上次仓位信息按现有生效时间结束
                historyInventory.setUpdateTime(nowDate);
                historyInventory.setUpdator(user.getName());
                historyInventoryDao.updateById(historyInventory);//保存原有盘存数据
                saveTip = "仓位:" + sysStorage.getName() + "\n材料:" + material.getNameNorms() + "\n期初值:" + StringUtils.formatDouble(historyInventory.getInitial() / 1000, 2)
                        + "吨,调整值:" + StringUtils.formatDouble(historyInventory.getAdjustment() / 1000, 2)
                        + "吨,购进值:" + StringUtils.formatDouble(netWeight / 1000, 2)
                        + "吨,消耗值:" + StringUtils.formatDouble((autoDosage + handDosage) / 1000, 2)
                        + "吨,目前库存:" + StringUtils.formatDouble(initial / 1000, 2) + "吨\n生效时间:" + takeTime;
                historyInventory.setMaterialId(dto.getMaterialId());
                historyInventory.setId(null);
                historyInventory.setCreateTime(nowDate);
                historyInventory.setAdjustment(0.0);
                historyInventory.setCreator(user.getName());
                historyInventory.setInitial(initial);
                historyInventory.setAdjustment(0.0);
                historyInventory.setCrease(0.0);
                historyInventory.setReduse(0.0);
                historyInventory.setStartDate(DateUtil.convertDate(takeTime));
                historyInventory.setCheckDate(nowDate);
                historyInventory.setStoreId(newStorageId);
                historyInventory.setMaterialId(newMaterialId);
                historyInventory.setControlStoreId(newControlStorageId);
            }
            historyInventory.setCreateTime(nowDate);
            historyInventory.setRemark(remark);
            if (!StringUtils.isNull(historyInventory.getId()) && sysStorage.getIsEnjoy().intValue() == 1) {//如果不是共享仓
                historyInventory.setId(null);
                code = historyInventoryDao.insert(historyInventory);
                if (code < 1)
                    throw new MessageCenterException("保存换料盘点记录错误");
            } else {
                code = historyInventoryDao.insert(historyInventory);
                if (code < 1)
                    throw new MessageCenterException("保存换料盘点记录错误");
            }
            if (!StringUtils.isNull(sysStorage.getInventoryTime()) && !StringUtils.isNull(takeTime)) {
                String inventoryTime = DateUtil.convertString(sysStorage.getInventoryTime());
                if (!inventoryTime.equals(takeTime)) {
                    sysStorage.setInventoryTime(DateUtil.convertDate(takeTime));
                    sysStorageDao.updateById(sysStorage);
                }
            }
            controlStorage.setMaxCapacity(sysStorage.getMaxCapacity());
            controlStorage.setFlag(ControlFlagEnum.ZC.getCode() + "");
            controlStorage.setControlCreateTime(DateUtil.convertString(nowDate));
			Long controlId = storERPMaterService.insertErpStore(line, controlStorage);
            if (controlId >= 0) {
                sysStorageMatch.setRelatedId(controlId);
                code = mapper.updateById(sysStorageMatch);
                if (code > 0)
                    return RestResultDto.success(saveTip);
            }
            throw new MessageCenterException("保存工控系统仓位关联信息异常");
        }
        throw new MessageCenterException("更新ERP仓位与工控仓位关联材料信息异常");
    }

    @Override
    public RestResultDto editStatus(Long id, Integer status, CacheUser user) {
        if (ObjectUtil.isEmpty(id)) {
            throw new SnakerException("标识不存在，请检查数据！");
        }
        SysStorageMatch sysStorageMatch = mapper.selectById(id);
        if (ObjectUtil.isEmpty(sysStorageMatch)) {
            throw new SnakerException("当前工控仓位数据不存在，请重新处理！");
        }
        sysStorageMatch.setStatus(status);
        sysStorageMatch.setUpdateTime(new Date());
        sysStorageMatch.setUpdator(user.getName());
        return RestResultDto.success("暂不提供禁用工控关联关系");
    }

    @Override
    public List<SysStorage> getStorageList(Long orgId,Long lineId) {
        QueryWrapper<SysStorage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysStorage::getOrgId,orgId);
        if (!StringUtils.isNull(lineId))
            queryWrapper.inSql("id", "select storage_id from sys_storage_line where status = 0 and line_id =" + lineId);
        queryWrapper.lambda().eq(SysStorage::getStatus,0);
        return sysStorageDao.selectList(queryWrapper);
    }

    @Override
    public List<MainMaterial> getMainMaterialList(Long orgId, Integer storeType, Long materialId) {
        QueryWrapper<MainMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MainMaterial::getOrgId,orgId);
        if (!StringUtils.isNull(storeType))
            queryWrapper.lambda().eq(MainMaterial::getStoreType, storeType);
        if (!StringUtils.isNull(materialId))
            queryWrapper.inSql("store_type", "select store_type from main_material " +
                    " where status = 0 and material_id = " + materialId);
        queryWrapper.lambda().eq(MainMaterial::getStatus,0);
        return mainMaterialDao.selectList(queryWrapper);
    }

    @Override
    public List<SysControlStorage> getControlStorageList(Long orgId, Long lineId) {
        QueryWrapper<SysControlStorage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysControlStorage::getOrgId,orgId);
        queryWrapper.lambda().eq(SysControlStorage::getLineId,lineId);
        queryWrapper.lambda().eq(SysControlStorage::getStatus,0);
        return sysControlStorageDao.selectList(queryWrapper);
    }

    @Override
    public List<SysLine> getLineList(Long orgId) {
        QueryWrapper<SysLine> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysLine::getOrgId,orgId);
        queryWrapper.lambda().eq(SysLine::getStatus,0);
        return sysLineDao.selectList(queryWrapper);
    }

    private Integer saveStorageLog(Long orgId, Long storageId, String oldStorage, String newStorage, Long materialId, String material,
                                   Long lineId, Integer type, Date takeTime, String creator, Date createTime) {
        SysStorageLog storageLog = new SysStorageLog(orgId, storageId, oldStorage,
                newStorage, materialId, material, lineId, type, takeTime, creator, createTime);
        storageLog.setStatus(0);
        Integer code = storageLogDao.insert(storageLog);
        if (code > 0)
            return 0;
        return -1;
    }

    /**
     * 新增控与ERP仓位对应工
     * @param line
     * @param controlStorage
     * @return
     */
    /*private Long insertErpStore(SysLine line, SysControlStorage controlStorage) {
        if (line.getProducer().equals("中青林")) {
            String sql = "insert into StorERPMater (Storage,Material,DatTim,Station,Amount,Flag) values (?,?,?,?,?,?)";
            Object[] obj = {controlStorage.getName(), controlStorage.getMaterialName(),
                    controlStorage.getControlCreateTime(), line.getControlLineId(),
                    controlStorage.getMaxCapacity(), controlStorage.getFlag()};
            JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLineJdbcTemplate(line);
            KeyHolder keyHolder = new GeneratedKeyHolder();
            jdbcTemplate.update(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps = connection.prepareStatement(sql, new String[]{"ID"});
                    for (int i = 0; i < obj.length; i++) {
                        ps.setObject(i + 1, obj[i]);
                    }
                    return ps;
                }
            }, keyHolder);
            Long taskId = keyHolder.getKey().longValue();
            if (taskId > 1)
                return taskId;
            return -1l;
        }

        return -1l;
    }*/
    /**
     * 修改控与ERP仓位对应
     * @param line
     * @param controlStorage
     * @return
     */
    /*private Long updateStore(SysLine line, SysControlStorage controlStorage) {
        if (line.getProducer().equals("中青林")) {
            JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLineJdbcTemplate(line);
            String querySql = "select * from StorERPMater  where station = " + line.getControlLineId()
                    + " and Storage = '" + controlStorage.getName() + "'";
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList(querySql);
            if (mapList == null || mapList.size() == 0) {
                return insertErpStore(line, controlStorage);
            } else {
                String updateSql = "update StorERPMater set Station=" + line.getControlLineId() + ",DatTim = '" + DateUtil.convertString(controlStorage.getCreateTime()) + "' ";
                if (!StringUtils.isNull(controlStorage.getName()))
                    updateSql += " ,Storage ='" + controlStorage.getName() + "' ";
                if (!StringUtils.isNull(controlStorage.getMaterialName()))
                    updateSql += " ,Material ='" + controlStorage.getMaterialName() + "' ";
                if (!StringUtils.isNull(controlStorage.getMaxCapacity()))
                    updateSql += " ,Amount ='" + controlStorage.getMaxCapacity() + "' ";
                if (!StringUtils.isNull(controlStorage.getFlag()))
                    updateSql += " ,Flag ='" + controlStorage.getFlag() + "' ";
                updateSql += " where id = " + mapList.get(0).get("ID");
                Integer code = jdbcTemplate.update(updateSql);
                if (code > 0)
                    return 0l;
                return -1l;
            }
        }
        return -1l;
    }*/

}
